package org.baizhiedu.jdk;

import org.baizhiedu.proxy.User;
import org.baizhiedu.proxy.a.UserService;
import org.baizhiedu.proxy.a.UserServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * ClassName: TestJdkProxy
 * Description:
 * Date: 2022/11/22 PM 1:56:45
 * <p>
 * project: spring5
 * package: org.baizhiedu.jdk
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class TestJdkProxy {

    /**
     * 1.借用类加载器 TestJdkProxy UserServiceImpl
     * 2.Jdk8.x 前
     * final UserService userService = new UserServiceImpl();
     *
     * @param args 参数
     */
    public static void main(String[] args) {
        // 1.创建原始对象
        UserService userService = new UserServiceImpl();

        // 2.Jdk 创建动态代理
        InvocationHandler handler = (proxy, method, args1) -> {
            System.out.println("----proxy log----");
            // 原始方法运行
            return method.invoke(userService, args1);
        };

        UserService userServiceProxy = ((UserService) Proxy.newProxyInstance(TestJdkProxy.class.getClassLoader(),
                userService.getClass().getInterfaces(), handler));

        userServiceProxy.login("suns", "123456");
        userServiceProxy.register(new User());
    }
}
